# -*- coding: utf-8 -*-

"""
@Datetime: 2019/2/9
@Author: Zhang Yafei
"""
import json
import traceback
from flask import request, g
from sqlalchemy.exc import IntegrityError
from common.libs.helper import getCurrentDate
from common.models.models import AppAccessLog
from common.models.models import AppErrorLog
from application import db


class LogService():
    @staticmethod
    def addAccessLog():
        target = AppAccessLog()
        target.target_url = request.url
        target.referer_url = request.referrer
        target.ip = request.remote_addr
        params = request.values.to_dict()
        target.query_params = '' if 'img' in params else json.dumps(params)
        if 'current_user' in g and g.current_user is not None:
            target.uid = g.current_user.id
        target.ua = request.headers.get('User-Agent')
        target.created_time = getCurrentDate()
        db.session.add(target)
        try:
            db.session.commit()
        except IntegrityError as e:
            traceback.print_exc()
            print(e)

        return True

    @staticmethod
    def addErrorLog(content):
        target = AppErrorLog()
        target.target_url = request.url
        target.referer_url = request.referrer
        params = request.values.to_dict()
        target.query_params = '' if 'img' in params else json.dumps(params)
        target.content = content
        target.created_time = getCurrentDate()
        db.session.add(target)
        try:
            db.session.commit()
        except IntegrityError as e:
            traceback.print_exc()
            print(e)

        return True